package com.neuedu.ruidaoexam.configUtils;


import java.util.concurrent.CountDownLatch;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
 
 
/**
 * redis配置
 * @Configuration spring框架中以java形式存在的配置文件
 * @EnableCaching spring框架开启缓存功能
 * @author 
 *
 */
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
	
	
	@Bean
	RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
			MessageListenerAdapter listenerAdapter) {
 
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
 
		return container;
	}
	
	//实例化一个StringRedisTemplate类  ,用于开启会话 ,向redis数据库进行操作
	@Bean
	StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
		return new StringRedisTemplate(connectionFactory);
	}
 
	@Bean
	MessageListenerAdapter listenerAdapter(Receiver receiver) {
		return new MessageListenerAdapter(receiver, "receiveMessage");
	}
 
	@Bean
	Receiver receiver(CountDownLatch latch) {
		return new Receiver(latch);
	}
 
	@Bean
	CountDownLatch latch() {
		return new CountDownLatch(1);
	}
 

	
	public class Receiver { 
		
 
		private CountDownLatch latch;
		
		@Autowired
		public Receiver(CountDownLatch latch) {
		    this.latch = latch;
		}
		
		public void receiveMessage(String message) {
		    latch.countDown();
		}
	}
	
	
}